package com.beone.admin.controller;

import com.beone.admin.entity.BaseUser;
import com.beone.admin.security.SysUser;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @title  控制器工具类
 * @Author 覃球球
 * @Version 1.0 on 2018/1/25.
 * @Copyright 长笛龙吟
 */
public class ControllerUtils {
    /**
     * 后台登录用户信息
     * @return
     */
    public static BaseUser getAdminUser(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if(session == null){
            return null;
        }

        BaseUser user = (BaseUser)session.getAttribute("adminUser");
        if(user == null){
            SysUser sysUser = getSysUserPermissions(request);
            if(sysUser == null){
                return null;
            }
            //设置用户登录会话信息
            session.setAttribute("adminUser", sysUser.getUser());
        }
        return  user;
    }

    /**
     * 后台登录用户及权限信息
     * @return
     */
    public static SysUser getSysUserPermissions(HttpServletRequest request){
        SecurityContextImpl securityContext = (SecurityContextImpl) request
                .getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        return (SysUser) securityContext.getAuthentication().getPrincipal();
    }
}
